package com.cbtx.tablet.fragments

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment

/**
 * author : joker.peng
 * e-mail : joker@fiture.com
 * date   : 2021/7/6 11:30 PM
 * desc   :
 */
abstract class CommonFragment : Fragment() {

    protected var mRootView: View? = null
    private var mIsCreateView = true

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        if (mRootView == null) {

            var obj = setLayout()
            if (obj is View) {
                mRootView = setLayout() as View
            } else if (obj is Int) {
                mRootView = inflater.inflate(setLayout() as Int, container, false)
            }

        } else {
            var parent = mRootView?.parent
            if (parent != null) {
                (parent as ViewGroup).removeView(mRootView)
            }
        }
        return mRootView
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        if (mIsCreateView) {
            initView(view, savedInstanceState)
            initData()
            mIsCreateView = false
        }
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        mIsPrepared = true
        lazyLoad()
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)

        lazyLoad()
    }

    // 设置布局
    protected abstract fun setLayout(): Any

    // 初始化view
    protected abstract fun initView(view: View?, savedInstanceState: Bundle?)

    // 初始化数据
    protected open fun initData() {}

    // 懒加载
    protected open fun lazyData() {}

    // ###############多状态布局处理################
    // 是否启动多状态布局
    protected open fun onIsMultiStateLayout(): Boolean {
        return false
    }


    // ################多状态布局################
    var mIsPrepared = false
    var mIsLazyLoad = false
    private fun lazyLoad() {
        if (userVisibleHint && mIsPrepared && !mIsLazyLoad) {
            lazyData()
            mIsLazyLoad = true
        }
    }

}